import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';

export async function GET() {
  try {
    // 从数据库获取所有公告
    const notices = await prisma.notice.findMany({
      orderBy: {
        releaseTime: 'desc'
      }
    });

    return NextResponse.json({ notices }, { status: 200 });
  } catch (error) {
    console.error('获取公告数据失败:', error);
    return NextResponse.json(
      { error: '获取公告数据失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { accountNum, content } = body;

    // 验证必要字段
    if (!accountNum || !content) {
      return NextResponse.json(
        { error: '账号和公告内容不能为空' },
        { status: 400 }
      );
    }

    // 创建新公告
    const newNotice = await prisma.notice.create({
      data: {
        accountNum,
        content,
        releaseTime: new Date()
      }
    });

    return NextResponse.json({ notice: newNotice }, { status: 201 });
  } catch (error) {
    console.error('创建公告失败:', error);
    return NextResponse.json(
      { error: '创建公告失败' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: Request) {
  try {
    const body = await request.json();
    const { noticeId, content } = body;

    if (!noticeId) {
      return NextResponse.json(
        { error: '公告ID不能为空' },
        { status: 400 }
      );
    }

    if (!content) {
      return NextResponse.json(
        { error: '公告内容不能为空' },
        { status: 400 }
      );
    }

    // 更新公告内容
    const updatedNotice = await prisma.notice.update({
      where: { noticeId: Number(noticeId) },
      data: { 
        content,
        releaseTime: new Date() // 更新发布时间
      }
    });

    return NextResponse.json({ notice: updatedNotice }, { status: 200 });
  } catch (error) {
    console.error('更新公告失败:', error);
    return NextResponse.json(
      { error: '更新公告失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // 从URL获取公告ID
    const id = request.nextUrl.searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '公告ID不能为空' },
        { status: 400 }
      );
    }
    
    // 删除公告
    await prisma.notice.delete({
      where: { noticeId: Number(id) }
    });
    
    return NextResponse.json(
      { message: '公告删除成功' },
      { status: 200 }
    );
  } catch (error) {
    console.error('删除公告失败:', error);
    return NextResponse.json(
      { error: '删除公告失败' },
      { status: 500 }
    );
  }
}